#include"List.h "
ListNode* BuyListNode(x)
{
	ListNode* newNode = (ListNode*)malloc(sizeof(ListNode));
	newNode->next=NULL;
	newNode->prev=NULL;
	newNode->data = x;
	return newNode;
}
ListNode* ListInit()
{
	ListNode* phead = BuyListNode(0);
	phead->next = phead;
	phead->prev = phead;
	return phead;
}

void ListPrint(ListNode* phead)
{
	struct ListNode* cur = phead->next;
	while (cur != phead)
	{
		printf("%d\t", cur->data);
		cur = cur->next;
	}
}

void ListPushBack(ListNode* phead,ListDataType x)
{
	ListInsert(phead->next, x);
	//ListNode* tail = phead->prev;
	//ListNode* newNode= BuyListNode(x);
	//newNode->next = phead;
	//newNode->prev = tail;
	//phead->prev = newNode;
	//tail->next = newNode;
}

void ListPopBack(ListNode* phead)
{
	ListEarse(phead->prev);
	//assert(phead);
	//ListNode* tail = phead->prev;
	//ListNode* tailPrev = tail->prev;
	//tailPrev->next = phead;
	//phead->prev = tailPrev;
	//free(tail);
	//tail = NULL;
}

void ListPopFront(ListNode* phead)
{
	ListEarse(phead->next);
	//assert(phead);
	//ListNode* first = phead->next;
	//ListNode* second = first->next;
	//phead->next = second;
	//second->prev = phead;
	//free(first);
	//first = NULL;
}

void ListPushFront(ListNode* phead, ListDataType x)
{
	ListInsert(phead->next, x);
	//ListNode* first = phead->next;
	//ListNode* newNode = BuyListNode(x);
	//phead->next = newNode;
	//newNode->prev = phead;
	//newNode->next = first;
	//first->prev = newNode;
}

ListNode* ListFind(ListNode* phead,ListDataType x)
{
	assert(phead);
	ListNode* cur = phead->next;
	ListNode* prev = cur;
	while (cur != phead)
	{
		if (cur->data == x)
			return cur;
		else
		{
			prev = cur;
			cur = cur->next;
		}
	}
	return NULL;
}

void ListInsert(ListNode* pos, ListDataType x)
{
	assert(pos);
	ListNode* prev = pos->prev;
	ListNode* newNode = BuyListNode(x);
	newNode->prev = prev;
	prev->next = newNode;
	newNode->next = pos;
	pos->prev = newNode;
}

void ListEarse(ListNode* pos)
{
	assert(pos);
	ListNode* prev = pos->prev;
	ListNode* next = pos->next;
	prev->next = next;
	next->prev = prev;
	free(pos);
	pos = NULL;
}

int ListEmtpy(ListNode* phead)
{
	return phead->next == phead ? 1: 0;
}

void ListDestroy(ListNode* phead)
{
	assert(phead);
	ListNode* cur = phead->next;
	while (cur != phead)
	{
		ListNode* next = cur->next;
		free(cur);
		cur = next;
	}
}

int ListSize(ListNode* phead)
{
	assert(phead);
	int size = 0;
	ListNode* cur = phead->next;
	while (cur != phead)
	{
		cur = cur->next;
		size++;
	}
	return size;
}